package com.app.twth.utils;

import static android.content.Context.INPUT_METHOD_SERVICE;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class EditTextUtil {
    /**
     * 显示键盘
     *
     * @param et 输入焦点
     */
    public static void showInput(Activity context, final EditText et) {
        et.requestFocus();
        InputMethodManager imm = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);
        imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
    }

    /**
     * 隐藏键盘
     */
    public static void hideInput(Activity context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);
        View v = context.getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    /**
     * 隐藏键盘
     */
    public static void setSelection(EditText et) {
        try {
            if (et.getText() == null) {
                return;
            }
            et.setSelection(et.getText().length());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static final int HIDE_KEYBOARD = 1;
    public static final int SHOW_KEYBOARD = 2;

    /**
     * 展示 或 隐藏 系统软键盘
     */
    public static void setKeyboardState(Activity context, int state, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            if (state == HIDE_KEYBOARD) {
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            } else if (state == SHOW_KEYBOARD) {
                view.requestFocus();
                imm.showSoftInput(view, 0);
            }
        }
    }
}
